<template>
  <div class="CreateTicket">
    <div class="content_box" v-if="is_loaded">
      <TicketView :fields="field_list" ref="TicketView" :attribute="sub_field_attribute" />
    </div>
    <div class="button_box">
      <van-button
        v-if="$route.query.page == 'myInitiation'"
        type="info"
        block
        class="button"
        @click="closeTicket"
      >
        关闭
      </van-button>
      <van-button
        type="info"
        block
        class="button"
        v-for="(btn, index) in init_state.transition" :key="index"
        @click="handleButton('form', btn.transition_id,index)"
      >
        {{btn.transition_name}}
      </van-button>
    </div>
  </div>
</template>

<script>
import { Dialog } from 'vant';
import TicketView from '../components/TicketView'
export default {
  components:{
    TicketView
  },
  data(){
    return{
      workflow_id:null,
      is_loaded: false,
      init_state:{},
      field_list:[],
      form_data:{},
      result:[],
      sub_field_attribute:{}
    }
  },
  created(){
    if(this.$route.query.page == "myInitiation"){//判断是否是从我的发起工单列表页跳转过来的
      this.workflow_id = this.$route.query.workflow_id - 0
      this.getTicketDetails(this.$route.query.ticket_id)
    }else{
      this.workflow_id = this.$route.query.id - 0
      this.initForm(this.$route.query.id)
    }
  },
  methods:{
    //获取工单详情以及操作
    getTicketDetails(id){
      this.$store.dispatch('api_get_ticket_transitions',this.$route.query.ticket_id).then(res=>{
        this.init_state.transition = res.data.data.value.reverse()
      })
      this.$store.dispatch('api_get_ticket_detail',id).then(res=>{
        // 排序
        this.field_list = res.data.data.value.field_list.sort((a,b)=>{
          return a.order_id - b.order_id
        })
        this.sub_field_attribute = res.data.data.value.state_info.label
        this.is_loaded = true
      })
    },
    // 初始化表单
    initForm(id){
      this.$store.dispatch('api_init_state', {id}).then(res=>{
        // 初始化数据存储
        this.init_state = res.data.data
        this.init_state.transition.reverse()
        this.sub_field_attribute = this.init_state.label
        // 排序
        this.field_list = res.data.data.field_list.sort((a,b)=>{
          return a.order_id - b.order_id
        })
        // console.log(JSON.stringify(this.field_list))
        this.is_loaded = true
      })
    },
    changeForm(object) {
      let form_data = {}
      Object.keys(object).forEach(key=>{
        if(object[key] != null){
          form_data[key] = object[key]
        }
      })
      return form_data
    },
    // 提交表单
    handleButton(form,id,index){
      let is_submit = index == 0?false:true
      this.form_data = this.$refs.TicketView.getFormData(is_submit)
      let fields = this.$refs.TicketView.getTitlefields()
      if(this.form_data){
        let data = {
          workflow_id: this.workflow_id,
          transition_id: id,
          title:{
            name: `${JSON.parse(this.$U.getCache('user')).alias}提交的${this.$route.query.workflow_name}`,
            fields
          }
        }
        let obj =  this.changeForm(this.form_data)
        Object.assign(data, obj)
        Object.keys(data).forEach(key=>{
          if(typeof data[key] == 'object'){
            data[key] = JSON.stringify(data[key])
          }
        })
        // 判断当前是创建工单还是修改工单  默认是创建工单api
        let ticketApi = 'api_post_ticket' 
        if(this.$route.query.page == "myInitiation"){
          ticketApi = 'api_post_reviseTicket'
          data.id = this.$route.query.ticket_id
        }
        
        let tipName = '创建'
        if(index == 0){
          tipName = '保存'
        }
        this.$store.dispatch(ticketApi, data).then(res => {
          this.$toast.success(tipName + '成功')
          if(this.$route.query.page != "myInitiation"){
            this.$router.push({name: 'myInitiation'})
          }else{
            this.$router.go(-1)
          }
        }).catch(error => {
          console.log(error.response)
          this.$toast.fail(tipName + '失败')
        })
      }
    },
    closeTicket(){
      Dialog.confirm({
        title: '提示',
        message: '您确定要关闭工单吗?'
      }).then(() => {
        this.$store.dispatch("api_post_close",this.$route.query.ticket_id).then(res=>{
          if(res.status == 200 ){
             this.$toast.success('关闭工单成功');
             this.$router.go(-1)
          }
        }).catch(err=>{
          console.log(err)
          this.$toast.fail('关闭工单失败，请稍后重试');
        })
      }).catch(() => {
        
      });
    },
  }
}
</script>

<style lang="less" scoped>
.mg_bottom_20{
  margin-bottom: 20px;
}
.CreateTicket{
  position: absolute;
  top: 0;
  bottom: 0;
  width: 100%;
  .content_box{
    position: absolute;
    top: 0;
    bottom: 50px;
    width: 100%;
    overflow: auto;
  }
  .button_box{
    position: absolute;
    bottom: 0;
    width: 100%;
    display: flex;
    height: 50px;
    background-color: #fff;
    flex-wrap: wrap;
    justify-content: space-between;
    .button{
      flex: 1;
      min-width: 25%;
      border-radius: 5px;
      font-size: 16px;
      margin: 3px 15px;
    }
  }
}
</style>
